import React, { Component, createRef } from "react"
import { Form, Input, Button, Space, message } from "antd"
import { PhoneOutlined, MailOutlined, InsuranceOutlined } from "@ant-design/icons"
import Captcha from "../../components/Captcha"
import axios from "../../http/axios"
import url from "../../config/url"
import { withRouter } from "react-router-dom"
class Mobileform extends Component {
    state = {
        key: "",
        requestId: '',
        time: 60,
        isSend: false
    }
    timer = null
    capRef = createRef()
    formRef = createRef()
    render() {
        return (
            <Form
                name="normal_login"
                className="login-form"
                initialValues={{
                    remember: true,
                }}
                onFinish={this.onFinish}
                ref={this.formRef}
            >
                <Form.Item
                    name="mobile"
                    rules={[
                        {
                            required: true,
                            // 支持正则表达式验证（切勿给表达式加引号）
                            pattern: /^1[3-9]\d{9}$/,
                            message: "请输入合法的手机号！",
                        },
                    ]}
                >
                    <Input prefix={<PhoneOutlined className="site-form-item-icon" />} placeholder="手机号" size="large" />
                </Form.Item>

                <Form.Item
                    name="captcha"
                    rules={[
                        {
                            required: true,
                            message: "请输入验证码！",
                        },
                    ]}
                >
                    {/* 务必确保Form.Item有且只有一个子元素 */}
                    <div>
                        <Space size="small">
                            <Input prefix={<InsuranceOutlined className="site-form-item-icon" />} type="text" placeholder="验证码" size="large" />
                            <Captcha h={40.14} saveKey={this.saveKey} ref={this.capRef} />
                        </Space>
                    </div>
                </Form.Item>

                <Form.Item
                    name="code"
                    rules={[
                        {
                            required: true,
                            message: "请输入短信验证码！",
                        },
                    ]}
                >
                    {/* 务必确保Form.Item有且只有一个子元素 */}
                    <div>
                        <Space size="middle">
                            <Input prefix={<MailOutlined className="site-form-item-icon" />} type="text" placeholder="短信验证码" size="large" />
                            <Button block size="large" disabled={this.state.time !== 60} onClick={this.sendCode}>{this.state.time === 60 ? '获取验证码' : `重新获取(${this.state.time})s`}</Button>
                        </Space>
                    </div>
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit" className="login-form-button" block size="large" disabled={!this.state.isSend}>
                        登录
                    </Button>
                </Form.Item>
            </Form>
        )
    }
    // 发送短信验证
    sendCode = () => {
        console.log(this.formRef);
        // 获取表单实例来获取手机号与captcha
        this.formRef.current.validateFields(['mobile', 'captcha']).then(res => {
            const { mobile, captcha } = res
            // 发送请求验证图形验证码 获取token
            axios.post(url.CaptchaVerify, { key: this.state.key, captcha }).then(ret => {
                console.log(ret);
                if (ret.data.errNo === 0) {
                    //获取token ret.data.context.token
                    // 发送请求来发送短信
                    axios.post(url.SendUrl, { token: ret.data.context.token, mobile, type: 0 }).then(rest => {
                        if (rest.data.errNo === 0) {
                            //短信发送成功，获取requestId
                            this.setState({
                                requestId: rest.data.requestId,
                                isSend: true  //将登录变为可点击项
                            })
                            //开始倒计时
                            this.timeDown()
                            message.success('短信下发成功')
                        } else {
                            //短信发送失败
                            message.success(rest.data.errText)
                            //刷新验证码
                            this.capRef.current.loadCaptcha()
                        }
                    })
                } else {
                    //图形验证码校验失败
                    message.error(ret.data.errText)
                    //刷新验证码
                    this.capRef.current.loadCaptcha()
                }
            })
        }).catch(e => { console.log(e); })
    }

    //倒计时
    timeDown = () => {
        if (this.state.time === 0) {
            this.setState({
                time: 60
            })
        } else {
            this.setState({
                time: this.state.time - 1
            })
            this.timer = setTimeout(() => {
                this.timeDown()
            }, 1000)
        }
    }
    //清除副作用
    componentWillUnmount() {
        clearTimeout(this.timer)
    }
    //从子中获取图形验证码的key
    saveKey = (key) => {
        this.setState({ key })
    }

    // onFinish：点击提交时候的回调函数（ajax发送的方法）
    // values：表单收到的数据，格式是一个对象
    onFinish = values => {
        // 获取需要的数据，实现登录
        const res = this.formRef.current.getFieldsValue(["mobile", "code"])
        // 追加requestId
        res.requestId = this.state.requestId
        axios.post(url.MobileVerfy, res).then(ret => {
            if (ret.data.errNo === 0) {
                // 成功了  message.success(content, [duration], onClose)
                message.success("登录成功！", 2, () => this.props.history.push("/dashboard"))
            } else {
                // 失败了
                message.error(ret.data.errText)
                // 刷新验证码
                this.capRef.current.loadCaptcha()
                // 禁用登录按钮
                this.setState({
                    isSend: false
                })
            }
        })
    }
}

export default withRouter(Mobileform)
